<template>
  <div class="page">
    <div style="display: flex;align-items: center">
      <div style="display: flex;flex-grow: 1;flex-direction: row;align-items: center;">
        <div @click="()=>{router.push('/')}" class="back" style="padding-left: 5px">
          <img src="@/assets/images/icons/left.png" alt="">
        </div>
        <Header title="订单确认" :back="true"/>

      </div>
      <div style="flex-grow: 1"></div>
      <van-icon name="home-o" @click="()=>{router.push('/')}"/>
      <div style="width: 20px"></div>
    </div>
    <div class="conform">
      <div class="img_bg">
        <img style="width:100%" src="/src/assets/images/index/scenic_bg.png" alt="">
      </div>
      <div class="commodity_information">
        <div class="commodity_information_img_box">
          <div class="img_box">
            <template v-if="!loading">
              <van-image lazy-load width="100%" height="100%"
                         :src="`${fileUrl}/${couponGoodsDetail?.productImage||userlist?.scenicSpot?.coverImage?.split(',')?.[0]}`"
                         radius=".8rem"/>
            </template>
            <van-skeleton v-else>
              <template #template>
                <div :style="{ display: 'flex', width: '100vw' }">
                  <van-skeleton-image :style="{ width: '100%', height: '8.7rem' }"/>
                </div>
              </template>
            </van-skeleton>
          </div>
          <div class="round round_left"/>
          <div class="round round_right"/>
        </div>
        <div class="order_info">
          <template v-if="!loading">
            <div class="order_info_header">
              <div v-if="couponGoodsDetail">
                {{ couponGoodsDetail.merchantName }}-{{ couponGoodsDetail.couponName }}
              </div>
              <div v-else>
                {{ userlist.scenicSpot?.scenicAreaName }}-{{ userlist.productClassifica?.classificationName }}
              </div>
            </div>
            <div class="order_info_time" v-if="route.query.productName!=='coupon'">
              <div class="cancel">
                <span>{{ route.query.productName === '活动预约' ? '活动' : '门店' }}地址 {{ buyInfo.buyAdress }}</span>
                <div class="line"></div>
              </div>

              <span class="order_info_time_list"
                    v-if="buyInfo.buyTime?.length">{{
                  route.query.productName === '活动预约' ? '活动' : '营业'
                }}时间</span>
              <div>
                <div v-for="(item,index) in buyInfo.buyTime" :key="index">

                  {{ item.timeHour.join('~') + ' ' + item.timeSlot.join(',') }}
                </div>
              </div>
            </div>
            <div class='order_inf_fitness' v-if="productName === '共享健身房' ">
              <span>预约时间: </span>
              <span>
					{{ getfitnessCurrentTime() }}
				</span>
            </div>
            <div class='order_inf_fitness' v-if="productName === 'coupon' ">
              <span>有效时间: </span>
              <span>
					{{ couponGoodsDetail?.validStartTime }}-{{ couponGoodsDetail?.validEndTime }}
				</span>
            </div>
            <div class='order_inf_fitness' v-if="productName === '1'||productName === '2' || productName === '3' ">
              <span>预约时间: </span>
              <span v-if="route.query.reservationTimeStart">
					{{decodeURIComponent( route.query.reservationTimeStart) }}~{{ decodeURIComponent(route.query.reservationTimeEnd) }}
				</span>
              <span v-else>
                <span v-if="route.query.billType">{{ route.query.billType }}</span>
				<span v-else-if="route.query.timeRangeVos?.length > 0">
					{{ route.query.timeRangeVos[0] }}
					{{ route.query.timeRangeVos?.length > 1 ? "等多个时间段" : '' }}
				</span>
                <span v-else>
                  包月
                </span>
              </span>
            </div>
          </template>
          <van-skeleton v-else>
            <template #template>
              <div :style="{ display: 'flex', width: '100%' }">
                <div :style="{ flex: 1}">
                  <van-skeleton-paragraph row-width="60%"/>
                  <van-skeleton-paragraph/>
                </div>
              </div>
            </template>
          </van-skeleton>
        </div>
      </div>
      <div class="card_box" v-if="productName === '活动预约' || productName === 'coupon'">
        <template v-if="!loading">
          <div class="header" v-if="productName === '活动预约'">
            门票种类
          </div>
          <div class="card">
            <div class="type">
              <div>
                <div class="type_name">{{ couponGoodsDetail?.couponName || userlist.goodsTickets?.ticketName }}</div>
                <span v-if=" userlist.goodsTickets?.deposit" class="tab label"
                      style="color: red;background: rgba(255, 102, 0, 0.1) !important;border-radius: 3px">
            押金￥{{ userlist.goodsTickets.deposit / 100 }}
          </span>
              </div>

              <div class="type_number">
                <div style="flex-grow: 1"></div>
                <div>
             		<span class="price">
             		  ￥
             		  <span class="price_number">{{couponGoodsDetail?.marketPrice|| userlist.goodsTickets?.marketPrice || 0 }}</span>
             		</span>

                </div>

                <van-stepper
                    v-model="ticketNumber"
                    integer
                    @change="handelvaluenumber"
                    :max="stepperMax || 99"
                />
              </div>
            </div>
          </div>
        </template>
        <van-skeleton v-else>
          <template #template>
            <div :style="{ display: 'flex', width: '100%', margin: '0 1.5rem' }">
              <div :style="{ flex: 1}">
                <van-skeleton-paragraph row-width="60%"/>
                <van-skeleton-paragraph/>
              </div>
            </div>
          </template>
        </van-skeleton>
      </div>
      <div class="card_box">
        <template v-if="!loading">
          <div class="header" v-if="PeopleNum > 0">
            出行人(请选择
            <span style="color: var(--van-primary-color)">{{ PeopleNum * ticketNumber }}</span>
            位出行人)
          </div>
          <div class="card">
            <div class="passenger">
              <div class="passenger_header" v-if="PeopleNum > 0">
                <div class="name">{{ userlist.goodsTickets?.ticketName }}</div>
                <div class="add" @click="shaopeople">
                  <van-icon name="plus"/>
                  添加
                </div>
              </div>
              <div class="passenger_list_box" v-show="matchedResults.length">
                <div class="list" v-for="item in matchedResults" :key="item.id">
                  <div>
                    <div class="name">{{ item.name }}</div>
                    <div class="id_card">
                      身份证：
                      {{ item.idCard }}
                    </div>
                  </div>
                  <img class="close_img" @click="handeldelinfo(item.id)" src="../../assets/images/icons/Frame60@2x.png"
                       alt="">
                </div>
              </div>
              <van-field class="field" v-model="tel" label="联系电话"
                         placeholder="请输入手机号" input-align="right" type="tel" @blur="handeljianc"/>
            </div>
          </div>
        </template>
        <van-skeleton v-else>
          <template #template>
            <div :style="{ display: 'flex', width: '100%', margin: '0 1.5rem' }">
              <div :style="{ flex: 1}">
                <van-skeleton-paragraph row-width="60%"/>
                <van-skeleton-paragraph/>
                <van-skeleton-paragraph/>
                <van-skeleton-paragraph/>
              </div>
            </div>
          </template>
        </van-skeleton>
      </div>
    </div>
    <div class="bottom_pay">
      <div class="bottom_pay_content">
        <template v-if="!loading">
          <div class="pay_button" @click="handelpay">
            {{
              userlist.goodsTickets?.marketPrice || userlist.goodsTickets?.deposit || couponGoodsDetail?.marketPrice ? '支付' : '领取'
            }}
          </div>
          <div v-if="getPrice()" class="price_box">
            应付金额：
            <span class="price">
          ￥
          <span class="number">
            {{ getPrice()?.toFixed(2) || "0" }}
          </span>
      </span>
          </div>
        </template>
        <van-skeleton v-else>
          <template #template>
            <div :style="{ display: 'flex', width: '50vw', margin: 'auto', }">
              <div :style="{ flex: 1}">
                <van-skeleton-paragraph/>
                <van-skeleton-paragraph/>
              </div>
            </div>
          </template>
        </van-skeleton>
      </div>
    </div>
    <Choicetraveler
        v-if="listpersons"
        @onSelect="onSelect" :showPopup="show"
        @closePopup="closePopup"
        :listpersons="listpersons"
        :valuenumber="PeopleNum * ticketNumber"
        :selectList="matchedResults"
    />
  </div>
</template>
<script setup>
import {ref, toRaw, onActivated} from 'vue'
import {showToast} from 'vant';
import {onBeforeRouteLeave, useRoute, useRouter} from "vue-router"
import Header from '@/components/header/Header.vue'
import Choicetraveler from '@/components/choicetraveler/Choicetraveler.vue'
import {showLoadingToast, closeToast} from 'vant'
import {buyInfoStore} from "@/stores/buyInfo.js"
import {spArr} from '@/utils/array-utils'

const router = useRouter()
const route = useRoute()
console.log('router', router, 'route', route)
const couponGoodsDetail = ref(null)

const buyInfo = buyInfoStore();
console.log('buyInfo', buyInfo.buyTime?.length)

if (!buyInfo.buyTime?.length) {
  // console.log('buyInfo',buyInfo)
  const str = localStorage.getItem('buyInfoStore');
  if (str) {
    const jsObj = JSON.parse(str);
    buyInfo.setBuyInfo(jsObj.buyTime, jsObj.buyAdress)
  }
}


const timeRegex = /(\d{2}:\d{2})-(\d{2}:\d{2})/;


defineOptions({
  name: 'scenicOrder',
})

const fileUrl = import.meta.env.VITE_FILE_URL

onBeforeRouteLeave((to, from) => {
  const needSaveRoute = ['addApedestrian', 'pedestrianedit']
  determineNeedSaveKeepALive(to, from, needSaveRoute, 'scenicOrder')
})

const userlist = ref([])
import api from '@/api/index.js'
import pay from '@/utils/pay.js'
import {isValidPhoneNumber} from '@/utils/index'
import {determineNeedSaveKeepALive} from "@/utils/routerKeepALive.js"
import {shouldHideBtn} from "@/utils/wx-utils.ts";
import moment from "moment";


const ticketNumber = ref(0)
if (Number(route?.query?.vanum)) {
  ticketNumber.value = Number(route.query.vanum)
}

// 返回价格计算
const getPrice = () => {
  if(route.query.productName==='coupon'){
    return  couponGoodsDetail?.value.marketPrice * ticketNumber.value
  }
  if (route.query.productName === '2' && route.query?.checkCard === '1') {
    return ((userlist.value.goodsTickets?.marketPrice + (userlist.value.goodsTickets?.deposit || 0) / 100) * route.query.timeRangeVos?.length)
  } else if (route.query.productName === '1' && route.query?.checkCard === '1') {
    return Number(route.query.price);
  } else {
    return (Number(ticketNumber.value) * (Number(userlist.value.goodsTickets?.marketPrice) + Number(userlist.value.goodsTickets?.deposit || 0) / 100))
  }
}

let data = route?.query?.dateS
let scenicId = route?.query?.scenicId //景点id
let productid = route?.query?.productid   //商品id
let ticketTypes = route?.query?.ticketTypes //分类id
let sessionid = route?.query?.sessionid  //场次id
let productName = route?.query?.productName
let fitnessCurrentTime = route?.query?.fitnessCurrentTime
const stepperMax = ref(0)
if (route?.query?.numberMax) {
  stepperMax.value = Number(route?.query?.numberMax)
}

const tel = ref(null)
const listpersons = ref([])
const idCardArray = ref([])

// 是否需要出行人
const PeopleNum = ref(0);

const show = ref(false)
const closePopup = () => {
  show.value = false;
};

// 获取健身房预约时间
function getfitnessCurrentTime() {
  if (fitnessCurrentTime[0] > 21) {
    return `2023-12-8 ${fitnessCurrentTime.join(':')} ~ 2023-12-9 ${Number(fitnessCurrentTime[0]) + 2 - 24 + ':' + fitnessCurrentTime[1]}`
  } else {
    return `2023-12-8 ${fitnessCurrentTime.join(':')} ~ 2023-12-0 ${Number(fitnessCurrentTime[0]) + 2 + ':' + fitnessCurrentTime[1]}`
  }
}

const matchedResults = ref([])
// const selectedPassengerList = ref([])
const onSelect = (val) => {
  matchedResults.value = val
//   selectedPassengerList.value = val
  idCardArray.value = toRaw(matchedResults.value).map((item) => item.id);
}

// 回传出行人信息

function shaopeople() {
  show.value = true
}

function handeldelinfo(id) {
  matchedResults.value = matchedResults.value?.filter(item => item.id !== id)
  idCardArray.value = toRaw(matchedResults.value).map((item) => item.id);
}

function handelvaluenumber(val) {
  if (val == stepperMax.value) {
    showToast(`限购${stepperMax.value}张`)
  }
}

// 获取出行人列表
function getapedestrianlist() {
  //不再需要出行人列表了
  return;

  if (route.query.productName === 'coupon') {
    return;
  }
  api.getapedestrian().then((res) => {
    listpersons.value = res.data
  }).finally(() => {

  })
}

onActivated(() => {
  getapedestrianlist()
})
getapedestrianlist()
// 更具多个id 预订不同景点
const loading = ref(false)

function geijdlist() {
  loading.value = true
  const params = {
    businessId: productid,//商品id
    frequencyId: sessionid,//场次id
    goodsKindsId: ticketTypes,//分类id
    scenicAreaId: scenicId,//景点id
    useTime: data
  }

  api.getReserveTickets(params).then((res) => {
    console.log("api.getReserveTickets，res.data.userTime", res.data.userTime)
    //不需要填写出行人了
    // PeopleNum.value = res.data.unitQuantity;

    userlist.value = res.data
  }).finally(() => {
    loading.value = false
  })
}

if (route.query.productName !== 'coupon') {
  geijdlist()
} else {
  //todo 获取优惠券详情
}

// 创建订单
function handelpay() {
  if (route.query.productName === 'coupon') {
    if (couponGoodsDetail.value) {
      showLoadingToast({
        message: '加载中...',
        forbidClick: true,
        duration: 0
      });
      api.couponorderpaymentsave(
          {
            "buyCount": ticketNumber.value,

            "phone": tel.value,
            "skuId": couponGoodsDetail.value.id
          }
      ).then(res => {
        if (res.code === '200') {
          if (couponGoodsDetail.value?.marketPrice) {
            _getIsCanPay(res.data)
          } else {
            console.log('0元购优惠券啦')
            router.push(`/activity-order/${res.data}?type=coupon`)
          }
        }
      }).finally(() => {
        closeToast()
      })
    }
    return;

  }
  if ((ticketNumber.value * PeopleNum.value) != idCardArray.value.length) {
    showToast(`请选择${ticketNumber.value * PeopleNum.value}位出行人`);
    return;
  }
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    duration: 0
  });
  let idCardIds = [];
  if (PeopleNum.value > 0) {
    idCardIds = spArr(idCardArray.value, PeopleNum.value, true);

  } else {
    idCardIds.push([]);
  }
  const data = {
    // idCardIds: toRaw(idCardArray.value),
    goodsDto: {
      buyCount: ticketNumber.value,
      frequencyId: sessionid,
      skuId: productid,
      idCardIdsTxt: idCardIds,
      useTime: userlist.value.userTime,
      startTime: route.query.productName !== '活动预约' ? (moment(decodeURIComponent(route.query.reservationTimeStart),'YYYY-MM-DD hh:mm:ss').format('YYYY-MM-DD HH:mm:ss')) : null,
      endTime: route.query.productName !== '活动预约' ? (moment(decodeURIComponent(route.query.reservationTimeEnd),'YYYY-MM-DD hh:mm:ss').format('YYYY-MM-DD HH:mm:ss')) : null,
    },
    phone: tel.value
  }
  if (userlist.value.unitQuantity === 1 && route.query.productName === '2') {
    data.goodsDto.timeRangeVos = route.query.timeRangeVos;
  }
  api.orderpaymentsave(data).then((res) => {
    if (res.code == 200 && res.data != null && res.success == true) {
      // pay.getPayld({ orderNumber: res.data })
      // _getIsCanPay(res.data)

      if (userlist.value.goodsTickets?.marketPrice || userlist.value.goodsTickets?.marketPrice?.deposit) {
        _getIsCanPay(res.data)
      } else {
        closeToast()
        router.push(`/activity-order/${res.data}`)
      }
    }
  })
  //  else if (tel.value && truelist.value == 1) {
  //     api.orderpaymentsave(data).then((res) => {
  //         if (res.code == 200 && res.data != null && res.success == true) {
  //             // pay.getPayld({ orderNumber: res.data })
  //           _getIsCanPay(res.data)
  //         }
  //     })
  // }

}

const _getIsCanPay = (orderNumber) => {
  api.getIsCanPay({orderNumber}).then((res) => {
    if (res.code === 200 || res.code === '200') {
      closeToast()
      pay.getPayld({
        orderNumber,
        finishUrl: shouldHideBtn() ? null : window.location.origin + '/#' + `activity-order/${orderNumber}?type=${route.query.productName}`,
        backUrl: location.href
      })
    }
  })
}
const truelist = ref()

// 检查手机号
function handeljianc() {
  if (tel.value) {
    if (isValidPhoneNumber(tel.value)) {
      truelist.value = 1
      return true
    } else {
      truelist.value = 2
      tel.value = ''
      showToast("请输入正确手机号")
    }
  }


}

function getCuoponGoodsDetail() {
  if (route.query.productName === 'coupon') {
    api.getCouponDetail({id: route.query.productid}).then(res => {
      if (res.code === '200') {
        couponGoodsDetail.value = res.data
      }
    })
  }
}

getCuoponGoodsDetail()
</script>

<style lang="scss" scoped>
:deep(.van-skeleton) {
  padding: 0;
}

:deep(.van-cell) {
  padding: 1rem;
}

:deep(.van-field__control) {
  font-size: 1.4rem;
  color: #333333;
}

:deep(.van-stepper__input) {
  min-width: 4rem;
  border-radius: 5px;
}

:deep(.van-stepper__plus) {
  border-radius: 5px;
}

:deep(.vvan-image__imgs) {
  object-fit: cover;
}

.page {
  height: 100vh;
  display: flex;
  flex-direction: column;

  .conform {
    // flex: 1;
    position: relative;
    z-index: 1;
    height: 100vh;
    overflow-y: auto;
    background-color: #F9F8F3;
    padding-bottom: 18rem;

    .img_bg {
      position: absolute;
      z-index: -1;
      top: 0;
      left: 0;
      width: 100%;
      height: 10vh;
    }

    .commodity_information {
      margin: 2.4rem 1.5rem 1.5rem 1.5rem;
      border-radius: 1rem;
      overflow: hidden;

      .commodity_information_img_box {
        position: relative;
        background: #ffffff;
        padding: 0 1.5rem;

        .img_box {
          height: 8.7rem;
          padding: 1.5rem 0;
          border-bottom: 1px dashed #eeeeee;

          :deep(.van-image__img) {
            object-fit: cover;
          }
        }

        .round {
          position: absolute;
          bottom: 0;
          width: 2.4rem;
          height: 2rem;
          background-color: #F9F8F3;
          border-radius: 50%;
        }

        .round_left {
          left: 0;
          transform: translateX(-50%) translateY(50%);
        }

        .round_right {
          right: 0;
          transform: translateX(50%) translateY(50%);
        }
      }

      .order_info {
        background: #ffffff;
        padding: 1.2rem 1.5rem 1.5rem 1.5rem;

        .order_info_header {
          font-size: 1.8rem;
          font-weight: bold;
          color: #333333;
          line-height: 2.5rem;
        }

        .order_info_time {
          display: flex;
          flex-wrap: wrap;
          margin-top: 0.6rem;
          font-size: 1.4rem;
          color: #999999;
          line-height: 2rem;

          .cancel {
            display: flex;
            align-items: center;
            font-size: 1.4rem;
            font-weight: normal;
            color: #999999;

            .line {
              width: .1rem;
              height: 1.4rem;
              background: #D9D9D9;
              margin: 0 .5rem;
            }
          }

          .order_info_time_list {
            margin-right: 1rem;
          }
        }

        .order_inf_fitness {
          font-size: 1.4rem;
          color: #999999;
          line-height: 2rem;
        }
      }
    }

    .card_box {
      margin-bottom: 1.5rem;

      .header {
        font-size: 1.4rem;
        font-weight: normal;
        color: #999999;
        margin: 0 1.5rem 1rem 1.5rem;
      }

      .card {
        background: #FFFFFC;
        box-shadow: 0 .7rem 1.5rem 0 rgba(54, 141, 88, 0.05);
        border-radius: 1rem;
        margin: 0 1.5rem;
        padding: 1.9rem 1.5rem;

        .type {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .type_name {
            font-size: 1.6rem;
            font-weight: bold;
            color: #333333;
          }

          .type_number {
            display: flex;
            align-items: center;
            min-width: 18rem;

            .price {
              font-size: 1.4rem;
              font-family: Alibaba PuHuiTi 2.0-75 SemiBold, Alibaba PuHuiTi 20;
              font-weight: bold;
              color: #ED6316;
              padding-right: 1rem;

              .price_number {
                font-size: 1.8rem;
              }
            }
          }
        }
      }

      .passenger {
        .passenger_header {
          display: flex;
          align-items: center;
          justify-content: space-between;

          .name {
            font-size: 1.6rem;
            font-weight: bold;
            color: #333333;
          }

          .add {
            height: 3rem;
            line-height: 3rem;
            background: rgba(0, 0, 0, 0.05);
            border-radius: .5rem;
            padding: 0 1.5rem;
          }

          .add:active {
            opacity: 0.5;
          }
        }

        .passenger_list_box {
          margin-top: 1.9rem;

          .list {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 1rem;
            background: rgba(79, 172, 145, 0.05);

            .name {
              font-size: 1.4rem;
              color: #333333;
              line-height: 2rem;
              font-weight: bold;
            }

            .id_card {
              font-size: 1.2rem;
              color: #666666;
              line-height: 1.4rem;
            }

            .close_img {
              width: 2.4rem;
              height: 2.4rem;
            }
          }
        }

        .field {
          background: rgba(79, 172, 145, 0.05);
          margin-top: 1.5rem;
          border-radius: .5rem;
        }
      }
    }
  }

  .bottom_pay {
    z-index: 1;
    position: absolute;
    bottom: 0rem;
    width: 100%;
    height: 6rem;
    background-color: #FFFFFF;

    .bottom_pay_content {
      display: flex;
      flex-direction: row-reverse;
      align-items: center;
      padding: 1rem 2rem 0 0;
      box-sizing: border-box;
    }

    .pay_button {
      height: 3.8rem;
      line-height: 3.8rem;
      background: var(--van-primary-color);
      border-radius: .5rem;
      opacity: 1;
      font-size: 1.6rem;
      color: #FFFFFF;
      padding: 0 3rem;
      margin-left: 1rem;
      white-space: nowrap;
    }

    .pay_button:active {
      background-color: var(--van-primary-button-active-color);
    }

    .price_box {
      display: flex;
      align-items: center;
      font-size: 1.4rem;
      color: #999999;

      .price {
        font-size: 1.4rem;
        color: #ED6316;
        line-height: 1.6rem;
        font-weight: bold;

        .number {
          font-size: 2.2rem;
          font-weight: bold;
          color: #ED6316;
          line-height: 2.6rem;
        }
      }
    }
  }
}

.tab {


  font-size: 1.3rem;


}

.label {
  margin-bottom: .8rem;
  margin-right: .5rem;
  padding: 0 .5rem;
  height: 1.7rem;
  line-height: 1.7rem;
  background: rgba(125, 188, 154, 0.2);
  border-radius: .3rem;
  font-size: 1.2rem;
  color: #35AD6D;
}
</style>
